﻿@page "/tests/datagrid"
<Row>
    <Column>
        <Card Margin="Margin.Is4.OnY">
            <CardHeader>
                <CardTitle>Data Grid</CardTitle>
            </CardHeader>
            <CardBody>
                <CardText>Combine diferent datagrid options</CardText>
            </CardBody>
            <CardBody>
                <Fields>
                    <Field>
                        <FieldLabel>
                        </FieldLabel>
                        <FieldBody>
                            <Check @bind-Checked="@editable">Editable</Check>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>
                        </FieldLabel>
                        <FieldBody>
                            <Check @bind-Checked="@sortable">Sortable</Check>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>
                        </FieldLabel>
                        <FieldBody>
                            <Check @bind-Checked="@filterable">Filterable</Check>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>
                        </FieldLabel>
                        <FieldBody>
                            <Check @bind-Checked="@showPager">Show Pager</Check>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>
                            Edit Mode
                        </FieldLabel>
                        <FieldBody>
                            <Select @bind-SelectedValue="@editMode">
                                <SelectItem Value="DataGridEditMode.Form">Form</SelectItem>
                                <SelectItem Value="DataGridEditMode.Inline">Inline</SelectItem>
                                <SelectItem Value="DataGridEditMode.Popup">Popup</SelectItem>
                            </Select>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>
                            Custom Search
                        </FieldLabel>
                        <FieldBody>
                            <TextEdit @bind-Text="@customFilterValue" />
                        </FieldBody>
                    </Field>
                </Fields>
            </CardBody>
            <CardBody>
                <DataGrid TItem="Employee"
                          Data="@dataModels"
                          EditMode="@editMode"
                          Editable="@editable"
                          Sortable="@sortable"
                          Filterable="@filterable"
                          ShowPager="@showPager"
                          RowInserted="@OnRowInserted"
                          RowUpdated="@OnRowUpdated"
                          RowRemoved="@OnRowRemoved"
                          UseInternalEditing="true"
                          @bind-SelectedRow="@selectedEmployee"
                          DetailRowTrigger="@((item)=>item.Salaries?.Count > 0 && item.Id == selectedEmployee?.Id)"
                          Striped="true"
                          Bordered="true"
                          Hoverable="true"
                          CustomFilter="@OnCustomFilter">
                    <DataGridAggregates>
                        <DataGridAggregate TItem="Employee" Field="@nameof( Employee.EMail )" Aggregate="DataGridAggregateType.Count">
                            <DisplayTemplate>
                                @($"Total emails: {context.Value}")
                            </DisplayTemplate>
                        </DataGridAggregate>
                        <DataGridAggregate TItem="Employee" Field="@nameof( Employee.Salary )" Aggregate="DataGridAggregateType.Sum" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
                        <DataGridAggregate TItem="Employee" Field="@nameof( Employee.IsActive )" Aggregate="DataGridAggregateType.TrueCount" />
                    </DataGridAggregates>
                    <DataGridColumns>
                        <DataGridCommandColumn TItem="Employee" Width="170px">
                            <NewCommandTemplate>
                                <Button Color="Color.Success" Clicked="@context.Clicked">New</Button>
                            </NewCommandTemplate>
                            <EditCommandTemplate>
                                <Button Color="Color.Primary" Clicked="@context.Clicked">Edit</Button>
                            </EditCommandTemplate>
                            <SaveCommandTemplate>
                                <Button Color="Color.Primary" Clicked="@context.Clicked">Save</Button>
                            </SaveCommandTemplate>
                            <DeleteCommandTemplate>
                                <Button Color="Color.Danger" Clicked="@context.Clicked">Delete</Button>
                            </DeleteCommandTemplate>
                            <CancelCommandTemplate>
                                <Button Color="Color.Secondary" Clicked="@context.Clicked">Cancel</Button>
                            </CancelCommandTemplate>
                            <ClearFilterCommandTemplate>
                                <Button Color="Color.Warning" Clicked="@context.Clicked">Clear Filter</Button>
                            </ClearFilterCommandTemplate>
                        </DataGridCommandColumn>
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Id )" Caption="#" Sortable="false" Width="60px" />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.FirstName )" Caption="First Name" Editable="true">
                            <FilterTemplate>
                                <TextEdit Placeholder="Search name" TextChanged="@(v=>context.TriggerFilterChange(v))" />
                            </FilterTemplate>
                        </DataGridColumn>
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.LastName )" Caption="Last Name" Editable="true" />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.EMail )" Caption="EMail" Editable="true" />
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.City )" Caption="City" Editable="true">
                            <FilterTemplate>
                                <Select TValue="string" SelectedValueChanged="@(e => context.TriggerFilterChange(e == "*" ? "" : e.ToString()))">
                                    <SelectItem Value="@("*")">All</SelectItem>
                                    @foreach ( var item in dataModels )
                                    {
                                        <SelectItem Value="@item.City">@item.City</SelectItem>
                                    }
                                </Select>
                            </FilterTemplate>
                        </DataGridColumn>
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Zip )" Caption="Zip" Editable="true" />
                        <DataGridDateColumn TItem="Employee" Field="@nameof( Employee.DateOfBirth )" DisplayFormat="{0:dd.MM.yyyy}" Caption="Date Of Birth" Editable="true" />
                        <DataGridNumericColumn TItem="Employee" Field="@nameof( Employee.Childrens )" Caption="Childrens" Editable="true" Filterable="false" />
                        <DataGridSelectColumn TItem="Employee" Field="@nameof( Employee.Gender )" Caption="Gender" Editable="true">
                            <DisplayTemplate>
                                @{
                                    var gender = ( context as Employee )?.Gender;

                                    @if ( gender == "M" )
                                    {
                                        @("Male")
                                    }
                                    else if ( gender == "F" )
                                    {
                                        @("Female")
                                    }
                                }
                            </DisplayTemplate>
                            <EditTemplate>
                                <Select TValue="string" SelectedValue="@((string)( ( (CellEditContext)context ).CellValue ))" SelectedValueChanged="@(( v ) => ( (CellEditContext)context ).CellValue = v)">
                                    <SelectItem TValue="string" Value="null"></SelectItem>
                                    <SelectItem TValue="string" Value="@("M")">Male</SelectItem>
                                    <SelectItem TValue="string" Value="@("F")">Female</SelectItem>
                                </Select>
                            </EditTemplate>
                        </DataGridSelectColumn>
                        <DataGridColumn TItem="Employee" Field="@nameof( Employee.Salary )" Caption="Salary" Editable="true" Width="140px" DisplayFormat="{0:C}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" TextAlignment="TextAlignment.Right">
                            <EditTemplate>
                                <NumericEdit TValue="decimal" Value="@((decimal)( ( (CellEditContext)context ).CellValue ))" ValueChanged="@(v => ( (CellEditContext)context ).CellValue = v)" />
                            </EditTemplate>
                        </DataGridColumn>
                        <DataGridCheckColumn TItem="Employee" Field="@nameof(Employee.IsActive)" Caption="Active" Editable="true" Filterable="false">
                            <DisplayTemplate>
                                <Check TValue="bool" Checked="context.IsActive" Disabled="true" ReadOnly="true" />
                            </DisplayTemplate>
                        </DataGridCheckColumn>
                    </DataGridColumns>
                    <DetailRowTemplate>
                        @{
                            var salaries = ( context as Employee ).Salaries;

                            <DataGrid TItem="Salary"
                                      Data="salaries"
                                      Sortable="false"
                                      ShowCaptions="false">
                                <DataGridCommandColumn TItem="Salary" />
                                <DataGridDateColumn TItem="Salary" Field="@nameof(Salary.Date)" Caption="Date" />
                                <DataGridNumericColumn TItem="Salary" Field="@nameof(Salary.Total)" Caption="Total" />
                            </DataGrid>
                        }
                    </DetailRowTemplate>
                </DataGrid>
            </CardBody>
        </Card>
    </Column>
</Row>
<Row>
    <Column>
        <Card>
            <CardHeader>
                <CardTitle>Selected Employee</CardTitle>
            </CardHeader>
            <CardBody>
                <Fields>
                    <Field>
                        <FieldLabel>First Name</FieldLabel>
                        <FieldBody>
                            <TextEdit ReadOnly="true" Text="@selectedEmployee?.FirstName"></TextEdit>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>Last Name</FieldLabel>
                        <TextEdit ReadOnly="true" Text="@selectedEmployee?.LastName"></TextEdit>
                    </Field>
                </Fields>
                <Fields>
                    <Field>
                        <FieldLabel>Email</FieldLabel>
                        <FieldBody>
                            <TextEdit ReadOnly="true" Text="@selectedEmployee?.EMail"></TextEdit>
                        </FieldBody>
                    </Field>
                    <Field>
                        <FieldLabel>City</FieldLabel>
                        <TextEdit ReadOnly="true" Text="@selectedEmployee?.City"></TextEdit>
                    </Field>
                </Fields>
            </CardBody>
        </Card>
    </Column>
</Row>
@code{
    DataGridEditMode editMode = DataGridEditMode.Form;
    bool editable = true;
    bool sortable = true;
    bool filterable = true;
    bool showPager = true;

    // TODO: add options to control the commands
    //bool newCommandAllowed = true;
    //bool editCommandAllowed = true;
    //bool saveCommandAllowed = true;
    //bool cancelCommandAllowed = true;
    //bool deleteCommandAllowed = true;
    //bool clearFilterCommandAllowed = true;

    Employee selectedEmployee;

    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EMail { get; set; }
        public string City { get; set; }
        public string Zip { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public int? Childrens { get; set; }
        public string Gender { get; set; }
        public decimal Salary { get; set; }
        public bool IsActive { get; set; }

        public List<Salary> Salaries { get; set; } = new List<Salary>();
    }

    public class Salary
    {
        public DateTime Date { get; set; }
        public decimal Total { get; set; }
    }

    // generated with https://mockaroo.com/
    List<Employee> dataModels = new List<Employee> {
        new Employee {Id = 1,FirstName = "Caro",LastName = "Nizard",EMail = "cnizard0@hc360.com",City = "Faīẕābād",Zip = null,Salary = 51724.19m, DateOfBirth = new DateTime(1983,5,8),
            Salaries = new List<Salary> {
                new Salary { Date = new DateTime(2019,1,6), Total = 6000 },
                new Salary { Date = new DateTime(2019,2,7), Total = 5005 },
                new Salary { Date = new DateTime(2019,3,5), Total = 3000 }
            }},
        new Employee {Id = 2,FirstName = "Matthew",LastName = "Labb",EMail = "mlabb1@ca.gov",City = "Xinxi",Zip = null,Salary = 65176.6m, Childrens=2},
        new Employee {Id = 3,FirstName = "Enos",LastName = "Clendennen",EMail = "eclendennen2@shareasale.com",City = "Listvyanskiy",Zip = "633224",Salary = 75602.48m, Childrens=1,
            Salaries = new List<Salary> {
                new Salary { Date = new DateTime(2019,2,7), Total = 4005 },
                new Salary { Date = new DateTime(2019,3,5), Total = 8000 }
            }},
        new Employee {Id = 4,FirstName = "Cirilo",LastName = "Douch",EMail = "cdouch3@thetimes.co.uk",City = "Wiset Chaichan",Zip = "84280",Salary = 88511.38m, IsActive = true },
        new Employee {Id = 5,FirstName = "Bibbie",LastName = "Prahm",EMail = "bprahm4@dropbox.com",City = "Nkandla",Zip = "3859",Salary = 41665.0m },
        new Employee {Id = 6,FirstName = "Ferd",LastName = "Bizzey",EMail = "fbizzey5@vimeo.com",City = "Arroyo Seco",Zip = "5196",Salary = 58632.74m, IsActive = true },
        new Employee {Id = 7,FirstName = "Annalee",LastName = "Mathie",EMail = "amathie6@qq.com",City = "Qi’an",Zip = null,Salary = 38622.71m },
        new Employee {Id = 8,FirstName = "Sarajane",LastName = "Sarney",EMail = "ssarney7@phoca.cz",City = "Wagini",Zip = null,Salary = 67163.94m },
        new Employee {Id = 9,FirstName = "Lissa",LastName = "Clemenzi",EMail = "lclemenzi8@si.edu",City = "Lijiang",Zip = null,Salary = 67078.77m },
        new Employee {Id = 10,FirstName = "Taber",LastName = "Kowal",EMail = "tkowal9@ustream.tv",City = "Muhos",Zip = "91501",Salary = 70385.0m },
        new Employee {Id = 11,FirstName = "Christyna",LastName = "Blaylock",EMail = "cblaylocka@gov.uk",City = "Kruševo",Zip = "34320",Salary = 20626.15m, Childrens=4 },
        new Employee {Id = 12,FirstName = "Honoria",LastName = "Stirtle",EMail = "hstirtleb@ox.ac.uk",City = "Muang Phôn-Hông",Zip = null,Salary = 48999.42m, Childrens=1 },
        new Employee {Id = 13,FirstName = "Gregory",LastName = "Sinden",EMail = "gsindenc@go.com",City = "Kampunglistrik",Zip = null,Salary = 38097.16m, Childrens=2 },
        new Employee {Id = 14,FirstName = "Obediah",LastName = "Stroban",EMail = "ostroband@nbcnews.com",City = "Almoínhas Velhas",Zip = "2755-163",Salary = 83997.47m },
        new Employee {Id = 15,FirstName = "Kellen",LastName = "Zanotti",EMail = "kzanottie@123-reg.co.uk",City = "Türkmenabat",Zip = null,Salary = 37339.0m },
        new Employee {Id = 16,FirstName = "Luelle",LastName = "Mowles",EMail = "lmowlesf@wikimedia.org",City = "Durham",Zip = "27717",Salary = 89879.64m },
        new Employee {Id = 17,FirstName = "Venita",LastName = "Petkovic",EMail = "vpetkovicg@twitpic.com",City = "Radoboj",Zip = "49232",Salary = 22979.32m },
        new Employee {Id = 18,FirstName = "Gates",LastName = "Neat",EMail = "gneath@youtu.be",City = "Solna",Zip = "170 77",Salary = 75811.63m },
        new Employee {Id = 19,FirstName = "Roland",LastName = "Frangleton",EMail = "rfrangletoni@umich.edu",City = "Tío Pujio",Zip = "5936",Salary = 58971.76m, Childrens=3 },
        new Employee {Id = 20,FirstName = "Ferdinande",LastName = "Pidcock",EMail = "fpidcockj@independent.co.uk",City = "Paris 11",Zip = "75547 CEDEX 11",Salary = 82223.65m },
        new Employee {Id = 21,FirstName = "Clarie",LastName = "Crippin",EMail = "ccrippink@lycos.com",City = "Gostyń",Zip = "63-816",Salary = 79390.13m },
        new Employee {Id = 22,FirstName = "Israel",LastName = "Carlin",EMail = "icarlinl@washingtonpost.com",City = "Poitiers",Zip = "86042 CEDEX 9",Salary = 36875.18m },
        new Employee {Id = 23,FirstName = "Christoper",LastName = "Moorton",EMail = "cmoortonm@gizmodo.com",City = "Jambangan",Zip = null,Salary = 76787.57m },
        new Employee {Id = 24,FirstName = "Trina",LastName = "Seamen",EMail = "tseamenn@foxnews.com",City = "Song",Zip = "54120",Salary = 43598.06m },
        new Employee {Id = 25,FirstName = "Douglass",LastName = "Amor",EMail = "damoro@house.gov",City = "Castillos",Zip = null,Salary = 49865.8m, Childrens=2, IsActive = true },
        new Employee {Id = 26,FirstName = "Reeta",LastName = "Acom",EMail = "racomp@fc2.com",City = "Baoping",Zip = null,Salary = 61296.4m },
        new Employee {Id = 27,FirstName = "Chandler",LastName = "Franzonetti",EMail = "cfranzonettiq@archive.org",City = "Emin",Zip = null,Salary = 67458.07m, Childrens=1 }
    };

    void OnRowInserted( SavedRowItem<Employee, Dictionary<string, object>> e )
    {
        //var employee = e.Item;

        //employee.Id = dataModels?.Max( x => x.Id ) + 1 ?? 1;

        //dataModels.Add( employee );
    }

    void OnRowUpdated( SavedRowItem<Employee, Dictionary<string, object>> e )
    {
        //var employee = e.Item;

        //employee.FirstName = (string)e.Values["FirstName"];
        //employee.LastName = (string)e.Values["LastName"];
        //employee.EMail = (string)e.Values["EMail"];
        //employee.City = (string)e.Values["City"];
        //employee.Zip = (string)e.Values["Zip"];
        //employee.DateOfBirth = (DateTime?)e.Values["DateOfBirth"];
        //employee.Childrens = (int?)e.Values["Childrens"];
        //employee.Gender = (string)e.Values["Gender"];
        //employee.Salary = (decimal)e.Values["Salary"];
    }

    void OnRowRemoved( Employee model )
    {
        //if ( dataModels.Contains( model ) )
        //{
        //    dataModels.Remove( model );
        //}
    }

    string customFilterValue;

    bool OnCustomFilter( Employee model )
    {
        if ( string.IsNullOrEmpty( customFilterValue ) )
            return true;

        return
            model.FirstName?.Contains( customFilterValue, StringComparison.OrdinalIgnoreCase ) == true
            || model.LastName?.Contains( customFilterValue, StringComparison.OrdinalIgnoreCase ) == true
            || model.EMail?.Contains( customFilterValue, StringComparison.OrdinalIgnoreCase ) == true;
    }
}
